package config.indoor.nexd.com.nexdmapconfig.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import config.indoor.nexd.com.nexdmapconfig.R;
import config.indoor.nexd.com.nexdmapconfig.adapter.MyExpandableListAdapter;
import config.indoor.nexd.com.nexdmapconfig.model.Expandable;
import config.indoor.nexd.com.nexdmapconfig.model.Mall;

/**
 * Created by wangxu on 16/2/24.
 */
public class MallListActivity extends AppCompatActivity implements
        AbsListView.OnScrollListener {

    private static final String TAG = "iphone";
    private static final String PRE = "IphoneExpandableListActivity--";
    @Bind(R.id.auto_complate)
    EditText search;
    @Bind(R.id.expandableListView)
    ExpandableListView listView;
    @Bind(R.id.topGroup)
    FrameLayout indicatorGroup;
    //    @Bind(R.id.mall_list)
//    ListView mallList;
//    MallAdapter mallAdapter;
    private ArrayList<Expandable> expandables = new ArrayList<>();
    private ArrayList<Expandable> searchMalls = new ArrayList<>();
    private MyExpandableListAdapter mAdapter;
    private int indicatorGroupId = -1;
    private int indicatorGroupHeight;

    private LayoutInflater mInflater;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_malls);
        ButterKnife.bind(this);
        expandables = getIntent().getParcelableArrayListExtra("malls");

        // 新加入的
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        indicatorGroup.setVisibility(View.INVISIBLE);
        mInflater.inflate(R.layout.list_item, indicatorGroup, true);
        mAdapter = new MyExpandableListAdapter(this, mInflater);
        mAdapter.addMalls(expandables);
        listView.setAdapter(mAdapter);
        listView.setOnScrollListener(this);
        listView.setGroupIndicator(null);

        // 设置对文本内容变化的监听
        search.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String content = s.toString().trim();
                searchMalls.clear();
                if (TextUtils.isEmpty(content)) {
                    mAdapter.addMalls(expandables);
                    mAdapter.notifyDataSetChanged();
                } else {
                    for (Expandable expandable : expandables) {
                        ArrayList<Mall> searchModel = new ArrayList<>();
                        for (Mall mall : expandable.getMalls()) {
                            if (mall.getMallName().contains(content)) {
                                searchModel.add(mall);
                            }
                        }
                        if (searchModel.size() > 0) {
                            searchMalls.add(new Expandable(expandable.getCityName(), searchModel));
                        }
                    }
                    mAdapter.addMalls(searchMalls);
                    mAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        // 设置child点击事件
        listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                Mall mall = mAdapter.getChild(groupPosition, childPosition);
                if (mall.isSelected()) {
                    mall.setIsSelected(false);
                } else {
                    mall.setIsSelected(true);
                }
                mAdapter.notifyDataSetChanged();
                return false;
            }
        });

//        // 设置对 item 的点击事件
//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//
//                Mall mallModel = mAdapter.getItem(position);
//                if (mallModel.isSelected()) {
//                    mallModel.setIsSelected(false);
//                } else {
//                    mallModel.setIsSelected(true);
//                }
//                mAdapter.notifyDataSetChanged();
//            }
//        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_back:
                finishActivity();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.back, menu);
        return super.onCreateOptionsMenu(menu);
    }

    public void finishActivity() {
        Intent data = this.getIntent();
        searchMalls.clear();
        ArrayList<Mall> resultModel = new ArrayList<>();
        for (Expandable expandable : expandables) {
            for (Mall mall : expandable.getMalls()) {
                if (mall.isSelected()) {
                    resultModel.add(mall);
                }
            }
        }
        data.putParcelableArrayListExtra("malls", resultModel);
        setResult(RESULT_OK, data);
        this.finish();
    }

    /**
     * here is very importance for indicator group
     */
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {

        final ExpandableListView listView = (ExpandableListView) view;
        /**
         * calculate point (0,0)
         */
        int npos = view.pointToPosition(0, 0);// 其实就是firstVisibleItem
        if (npos == AdapterView.INVALID_POSITION)// 如果第一个位置值无效
            return;

        long pos = listView.getExpandableListPosition(npos);
        int childPos = ExpandableListView.getPackedPositionChild(pos);// 获取第一行child的id
        int groupPos = ExpandableListView.getPackedPositionGroup(pos);// 获取第一行group的id
        if (childPos == AdapterView.INVALID_POSITION) {// 第一行不是显示child,就是group,此时没必要显示指示器
            View groupView = listView.getChildAt(npos
                    - listView.getFirstVisiblePosition());// 第一行的view
            indicatorGroupHeight = groupView.getHeight();// 获取group的高度
            indicatorGroup.setVisibility(View.GONE);// 隐藏指示器
        } else {
            indicatorGroup.setVisibility(View.VISIBLE);// 滚动到第一行是child，就显示指示器
        }
        // get an error data, so return now
        if (indicatorGroupHeight == 0) {
            return;
        }
        // update the data of indicator group view
        if (groupPos != indicatorGroupId) {// 如果指示器显示的不是当前group
            mAdapter.getGroupView(groupPos, listView.isGroupExpanded(groupPos),
                    indicatorGroup.getChildAt(0), null);// 将指示器更新为当前group
            indicatorGroupId = groupPos;
            Log.e(TAG, PRE + "bind to new group,group position = " + groupPos);
            // mAdapter.hideGroup(indicatorGroupId); // we set this group view
            // to be hided
            // 为此指示器增加点击事件
            indicatorGroup.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    listView.collapseGroup(indicatorGroupId);
                }
            });
        }
        if (indicatorGroupId == -1) // 如果此时grop的id无效，则返回
            return;

        /**
         * calculate point (0,indicatorGroupHeight) 下面是形成往上推出的效果
         */
        int showHeight = indicatorGroupHeight;
        int nEndPos = listView.pointToPosition(0, indicatorGroupHeight);// 第二个item的位置
        if (nEndPos == AdapterView.INVALID_POSITION)//如果无效直接返回
            return;
        long pos2 = listView.getExpandableListPosition(nEndPos);
        int groupPos2 = ExpandableListView.getPackedPositionGroup(pos2);//获取第二个group的id
        if (groupPos2 != indicatorGroupId) {//如果不等于指示器当前的group
            View viewNext = listView.getChildAt(nEndPos
                    - listView.getFirstVisiblePosition());
            showHeight = viewNext.getTop();
            Log.e(TAG, PRE + "update the show part height of indicator group:"
                    + showHeight);
        }

        // update group position
        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) indicatorGroup
                .getLayoutParams();
        layoutParams.topMargin = -(indicatorGroupHeight - showHeight);
        indicatorGroup.setLayoutParams(layoutParams);
    }

    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }
}

